import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:device_info/device_info.dart';

///
/// 工具函数集合
///
class ToolFunc {
  /// 根据时间戳生成随机字符串
  static String randomKeyByTimestamp([int strlenght = 6]) {
    final alphabet =
        'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
    final timestamp = DateTime.now().microsecondsSinceEpoch;
    String left = '';
    for (var i = 0; i < strlenght; i++) {
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return '$timestamp$left';
  }

  ///
  /// 判断是否json字符串
  ///
  static bool isJson(str) {
    try {
      json.decode(str);
    } catch (e) {
      return false;
    }
    return true;
  }

  ///
  /// 解压json字符串
  /// 非json字符串返回null
  ///
  static toJson(str) {
    return isJson(str) ? json.decode(str) : null;
  }

  /// 获取设备唯一id
  static Future<String> deviceID() async {
    DeviceInfoPlugin phoneInfo = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await phoneInfo.androidInfo;
      return androidInfo.androidId;
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await phoneInfo.iosInfo;
      return iosInfo.identifierForVendor;
    } else {
      return null;
    }
  }

  /// 固定长度分割数组
  static List<List<T>> splitList<T>(List<T> list, int len) {
    if (len <= 1) {
      return [list];
    }

    List<List<T>> result = List();

    int index = 1;

    while (true) {
      if (index * len < list.length) {
        List<T> temp = list.skip((index - 1) * len).take(len).toList();

        result.add(temp);

        index++;

        continue;
      }

      List<T> temp = list.skip((index - 1) * len).toList();
      result.add(temp);

      break;
    }

    return result;
  }

  /// 节流
  /// ```
  /// callback 回调函数
  /// duration 节流间隔 默认500毫秒
  /// ```
  static Function([dynamic]) throttle(
    Function(dynamic) callback, {
    Duration duration = const Duration(milliseconds: 500),
  }) {
    bool canRun = true;
    return ([agrs]) {
      if (canRun) {
        callback(agrs);
        Timer(duration, () => canRun = true);
        canRun = false;
      }
    };
  }

  /// 手动防抖
  /// ```
  /// callback(reset, agrs) 回调函数
  /// reset 重置状态的方法
  /// agrs 可能传过来的参数
  /// ```
  static Function([dynamic]) debounce(Function(Function(), dynamic) callback) {
    bool canRun = true;

    // 恢复可执行状态
    reset() => canRun = true;

    return ([agrs]) {
      if (canRun) {
        canRun = false;
        callback(reset, agrs);
      }
    };
  }

  /// 用于查询对方id
  static String queryTargetId(String id1, String id2, String value) {
    List<String> list = [id1, id2];
    list.remove(value);
    return list.length == 1 ? list[0] : null;
  }

  /// 判断是否int
  static bool isInt(str) {
    try {
      int.parse(str);
      return true;
    } on FormatException {
      return false;
    }
  }

  /// 判断是否double
  static bool isDouble(str) {
    try {
      double.parse(str);
      return true;
    } on FormatException {
      return false;
    }
  }

  /// 判断当前环境
  static bool get release => const bool.fromEnvironment("dart.vm.product");

  /// 正确的 ... 省略包括emoji的文本
  static String maxLength(String str, int len) {
    // 删除emoji表情
    var sRunes = str.runes;
    return sRunes.length > len ?  String.fromCharCodes(sRunes, 0, sRunes.length - len) +"...":str;
  } 
}
